package com.fz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fz.entity.Category;
import com.fz.mapper.CategoryMapper;
import com.fz.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 存储商品类别信息 服务实现类
 * </p>
 *
 * @author hyr
 * @since 2025-06-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> getList() {
        return getByParentId(0L);
    }
    @Override
    public List<Category> getByParentId(Long parentId) {
        //通过父id 0 来获取顶层品牌
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<Category> list = this.list(wrapper);
        //递归查询剩余的孩子
        for (Category category : list) {
            List<Category> children = getByParentId(category.getId());
            category.setChildren(children);
        }
        return list;
    }
    //返回父节点下的所有叶子节点
    @Override
    public List<Category> findAllLeafNodes(Long parentId) {
        List<Category> leafNodes = new ArrayList<>();
        findAllLeaf(parentId, leafNodes);
        return leafNodes;
    }
    //递归查询父节点下的所有叶子节点
    private void findAllLeaf(Long parentId, List<Category> leafNodes) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        if (categories.isEmpty()) {
            leafNodes.add(categoryMapper.selectById(parentId));
        } else {
            for (Category category : categories) {
                findAllLeaf(category.getId(), leafNodes);
            }
        }
    }
}
